package com.tiantian.framework.config;

import com.tiantian.framework.config.Interceptor.WSHandshakeInterceptor;
import com.tiantian.framework.handler.NoticeWebSocketHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean;

import javax.annotation.Resource;

/**
 * WebSocket配置文件
 */
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
    /**
     * 注入拦截器
     */
    @Resource
    private WSHandshakeInterceptor WSHandshakeInterceptor;


    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
        webSocketHandlerRegistry
                // 添加myHandler消息处理对象，和websocket访问地址
                .addHandler(myHandler(), "/jx/notice")
                // 设置允许跨域访问
                .setAllowedOrigins("*")
                // 添加拦截器可实现用户链接前进行权限校验等操作
                .addInterceptors(WSHandshakeInterceptor);
    }

    /**
     * 以下是配置WebSocket的配置属性 消息缓冲区大小，空闲超时
     */
    @Bean
    public ServletServerContainerFactoryBean createWebSocketContainer() {
        ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
        container.setMaxTextMessageBufferSize(8192);
        container.setMaxBinaryMessageBufferSize(8192);
        container.setMaxSessionIdleTimeout(300000L);
        return container;
    }

    @Bean
    public WebSocketHandler myHandler() {
        return new NoticeWebSocketHandler();
    }
}
